package com.moefor.clover.service;

import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.moefor.clover.dao.UserDao;
import com.moefor.clover.model.User;
import com.moefor.clover.model.element.Picture;
import com.moefor.clover.util.Encrypt;
import com.moefor.clover.util.MessagePackager;

@Service
public class UserService {
	@Resource
	private UserDao userDao;
	
	public UserDao getUserDao() {
		return userDao;
	}

	public MessagePackager val(String username, String password){
		MessagePackager msgPack = new MessagePackager();
		password = Encrypt.MD5(password);
		if(userDao.val(username, password)){
			msgPack.setState(true);
			msgPack.setData(userDao.get(username));
		}else{
			msgPack.setState(false);
			if(userDao.exist(username)){
				msgPack.setData("密码错误.");
			}else{
				msgPack.setData("账号不存在.");
			}
		}
		return msgPack;
	}
	
	public MessagePackager get(String username){
		MessagePackager msgPack = new MessagePackager(false, null, "未知错误!");
		msgPack.setData(userDao.get(username));
		if(msgPack.getData() == null){
			msgPack.setData("用户不存在");
		}else msgPack.setState(true);
		return msgPack;
	}
	public MessagePackager get(int id){
		MessagePackager msgPack = new MessagePackager(false, null, "未知错误!");
		msgPack.setData(userDao.get(id));
		if(msgPack.getData() == null){
			msgPack.setData("用户不存在");
		}else msgPack.setState(true);
		return msgPack;
	}
	
	public MessagePackager regist(
			String username,
			String password,
			String email,
			String tel){
		MessagePackager msgPack = new MessagePackager();
		User user = new User();
		password = Encrypt.MD5(password);
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		user.setTel(tel);
		Picture pic = new Picture();
		pic.setUrl("res/img/default.jpg");
		user.setAvator(pic);
		if(userDao.add(user)){
			msgPack.setState(true);
			msgPack.setData(userDao.get(username));
		}else{
			msgPack.setState(false);
			if(userDao.exist(username)){
				msgPack.setData("用户名已被注册!");
			}else{
				msgPack.setData("注册失败, 未知错误.");
			}
		}
		return msgPack;
	}
	
	public MessagePackager update(
			int id,
			String password,
			String email,
			String tel,
			String avatorUrl){
		MessagePackager msgPack = new MessagePackager();
		User user = userDao.get(id);
		if(user == null){
			msgPack.setState(false);
			msgPack.setData("用户不存在.");
			return msgPack;
		}
		password = Encrypt.MD5(password);
		user.setPassword(password);
		user.setEmail(email);
		user.setTel(tel);
		Picture pic = new Picture();
		pic.setUrl(avatorUrl);
		user.setAvator(pic);
		if(userDao.update(user)){
			msgPack.setState(true);
			msgPack.setData("修改成功！");
		}else{
			msgPack.setState(false);
			
			msgPack.setData("修改失败, 未知错误.");
			
		}
		return msgPack;
	}
}
